﻿using System;
using System.ComponentModel;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using OpenWaves.Web;

namespace OpenWaves.ActivityFeed.Web.Controls
{
    [ControlBuilder(typeof(PlaceHolderControlBuilder))]
    //[ParseChildren(true)]
    //[PersistChildren(true)]
    [DefaultProperty("Topic")]
    [ToolboxData("<{0}:ActivityFeedSubscribeButton runat=server></{0}:ActivityFeedSubscribeButton>")]
    public class ActivityFeedSubscribeButton : PlaceHolder
    {
        public ActivityFeedSubscribeButton(): base()
        {
            this.FollowText = "Follow";
            this.UnfollowText = "Unfollow";
        }

        #region properties

        [Bindable(true)]
        [Category("Activity Feed")]
        [Localizable(true)]
        public Topic Topic { get; set; }

        [Bindable(true)]
        [Category("Activity Feed")]
        [Localizable(true)]
        public string FollowText { get; set; }

        [Bindable(true)]
        [Category("Activity Feed")]
        [Localizable(true)]
        public string UnfollowText { get; set; }

        #endregion

        public string ScriptsPlaceholderControlId { get; set; }
        
        protected override void CreateChildControls()
        {
            this._scriptContent = null;
            if (!string.IsNullOrEmpty(this.ScriptsPlaceholderControlId))
            {
                var scriptPlaceholder = this.Page.FindControlRecursive(this.ScriptsPlaceholderControlId);
                Contract.Assert(scriptPlaceholder != null,
                                string.Format(CultureInfo.InvariantCulture, "Cannot find script control: '{0}'", this.ScriptsPlaceholderControlId));
                this._scriptContent = new Literal();
                scriptPlaceholder.Controls.Add(this._scriptContent);
            }
        }
        
        private Literal _scriptContent;

        protected override void Render(HtmlTextWriter writer)
        {
            Contract.Requires<ArgumentNullException>(
                this.Topic != null && string.IsNullOrEmpty(this.Topic.ToString()) == false, "Topic is empty");

            var userIdentityProvider = ServiceLocator.Resolve<IUserIdentityProvider>();
            var activityFeedService = ServiceLocator.Resolve<IActivityFeedService>();

            var subscriptions = activityFeedService.GetSubscriber(userIdentityProvider.Identity.Name).Subscriptions;
            var hasTopicSubscription = subscriptions.Any(s => this.Topic == s);

            writer.AddAttribute("data-topic", this.Topic.ToString());
            writer.AddAttribute("class", "_af-subscribe-button" + (hasTopicSubscription ? " subscribed" : ""));
            writer.AddAttribute("href", "javascript:void(0);");
            writer.AddAttribute(HtmlTextWriterAttribute.Id, this.ClientID);
            writer.RenderBeginTag(HtmlTextWriterTag.A);

            if (this.Controls.Count == 0)
            {
                writer.AddAttribute(HtmlTextWriterAttribute.Class, "subscribe");
                writer.RenderBeginTag(HtmlTextWriterTag.Span);
                writer.WriteEncodedText(this.FollowText);
                writer.RenderEndTag();

                writer.AddAttribute(HtmlTextWriterAttribute.Class, "unsubscribe");
                writer.RenderBeginTag(HtmlTextWriterTag.Span);
                writer.WriteEncodedText(this.UnfollowText);
                writer.RenderEndTag();
            }
            else
            {
                base.Render(writer);
            }
            writer.RenderEndTag();
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            var script = string.Format(CultureInfo.InvariantCulture, "$('#{0}').subscribeUnsubscribeButton();", this.ClientID);
            if (this._scriptContent == null)
            {
                this.Page.ClientScript.RegisterStartupScript(typeof(ActivityFeedSubscribeButton), this.UniqueID, script, true);
            }
            else
            {
                this._scriptContent.Text = string.Format(CultureInfo.InvariantCulture, "<script type='text/javascript'>//<![CDATA[\r\n\r\n{0}\r\n//]]></script>",
                                                         script);
            }
        }
    }
}
